#!/usr/bin/python2.4
# jhebert@cs.washington.edu

import sys
import threading
import Queue


class WorkerThread:
  """One thread per workerThread class will perfrom the
  computations for the nodes. """

  def __init__(self, threadPool):
    self.threadPool = threadPool
    self.workQueue = Queue.Queue()
    self.thread = None

  def AddToQueue(self, flag, item):
    """ Add a job to run onto the work queue for this worker. """
    self.workQueue.put((flag, item))

  def SetThread(self, thread):
    """ Set the thread that will be be running this queue.
    Not needed to run, but might be helpful somehow. """
    self.thread = thread

  def Stop(self):
    """ Insert a job into the queue telling the thread to quit. """
    self.workQueue.put(('quit', Exiter(self.threadPool)))

  def Run(self):
    """ Block until there is a waiting job on the queue, and then execute
    the run method of that object.
    Quits are done by inserting an 'Exiter' object into the queue."""
    while(1):
      self.threadPool.logging.put('waiting on queue')
      flag, item = self.workQueue.get() # this line blocks!
      toAppend = str(item)+', '+str(flag)
      self.threadPool.logging.put('workerThread is running:'+toAppend)
      item.Run()
      self.threadPool.logging.put('workerThread done running:'+toAppend)
      self.threadPool.ReturnWorker(self)


class Exiter:
  """ When run this class exits the thread without error.
  This allows the main run loop to always execute the object
  and not check for a runtime exit flag. Slightly more graceful. """
  def __init__(self, threadPool):
    self.threadPool = threadPool

  def Run(self):
    self.threadPool.logging.put('worker is exiting')
    sys.exit(0)
